﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
using System.Web.Mvc;
using System.IO;

namespace Quizz.Library.Actions
{
    public abstract class BasicAction
    {
        protected ViewDataDictionary ViewData;
        protected System.Web.Mvc.Controller Controller;
        protected HttpRequest Request;
        protected HttpServerUtility Server;
        protected HttpSessionState Session;

        public BasicAction(System.Web.Mvc.Controller controller)
        {
            if (controller == null) throw new ArgumentNullException("controller");

            this.Controller = controller;
            this.ViewData = controller.ViewData;
            Request = HttpContext.Current.Request;
            Server = HttpContext.Current.Server;
            Session = HttpContext.Current.Session;
        }

        public string RenderPartial(string patialName, object data)
        {
            if (string.IsNullOrEmpty(patialName))
            {
                patialName = this.Controller.ControllerContext.RequestContext.RouteData.GetRequiredString("action");
            }
            ViewData.Model = data;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(Controller.ControllerContext, patialName);
                var viewContext = new ViewContext(Controller.ControllerContext, viewResult.View, ViewData, Controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
